# -*- coding: UTF-8 -*-
# @Time : 2022/1/5 0005 14:29
# @Author : lyw
# @Remark :
import re

try:
    from opm_pyirm import GetStatusById
except ImportError:
    try:
        from bsmiddle import GetStatusById
    except ImportError:
        def GetStatusById(*args):
            return 1, 2

from db.common.IOTManager.PowerCabinet.power_cabinet import PowerDeviceSelectDB, PowerDeviceListDB, \
    PowerDeviceRetrieveDB
from model.common.IOTManager.iot_base import SRoomIOTMiddleModel
from server.common.IOTManager.GasDetector.gas_detector import GASDeviceSelectServer
from utils.classes.custom_exception import VerifyError
from index import _


class PowerDeviceSelectServer(GASDeviceSelectServer):
    __db__ = PowerDeviceSelectDB
    __model__ = SRoomIOTMiddleModel

    def device_info(self, device_list, state_dict: dict = None):
        """

        @param device_list:
        @return:
        """
        res_device_data = []
        if state_dict is None:
            state_dict = {"state": 1}
        if state_dict["state"] != 2:
            state_dict["state"] = 1

        for device_data in device_list:
            if state_dict is not None:
                status = GetStatusById(device_data["code"])
                if isinstance(status ,int):
                    status = status
                else:
                    status = status[1]
                if status != 1:
                    state_dict["state"] = 2
            device_info_dict = self.device_base_info(device_data)
            device_info_dict["inlet_voltage"] = []
            device_info_dict["outlet_current"] = []
            # 获取告警信息
            self.query_data(device_info_dict, device_data)
            res_device_data.append(device_info_dict)
        return res_device_data

    def query_data(self, dev_info_dict, device_data):
        tmp_conf_dict = {"in": "inlet_voltage", "out": "outlet_current"}
        tmp = self.db.read_template()
        device_type = device_data["mxdevicetype"].rsplit("\\", 1)[1]

        if not tmp.get(device_type):
            return
        device_type = tmp[device_type]

        record_dict = self.get_table_data(device_data["sub_monitor"], days=3, count=1)
        for tmp_key, tmp_value in tmp_conf_dict.items():
            for tmp_dict in device_type.get(tmp_key, {}):
                if not record_dict.get(tmp_dict["name"]):
                    continue
                record_value_dict = record_dict[tmp_dict["name"]][0]
                dev_info_dict[tmp_value].append(
                    {"phace": tmp_dict["mxlabel"], "data": record_value_dict[tmp_dict["code"]],
                     "unit": tmp_dict["mxunit"]})

    def get_table_data(self, sub_monitor, **kwargs):
        """
        获取所有的table表中的数据
        @param sub_monitor:
        @return:
        """
        record_dict = {}
        for monitor_key, monitor_data in sub_monitor.items():
            record_dict[monitor_data] = self.db.query_table_data(code=monitor_key, **kwargs)
        return record_dict

    def device_base_info(self, device_data):
        """
        返回设备基础信息
        @param device_data:
        @return:
        """
        status = GetStatusById(device_data["code"])
        if isinstance(status ,int):
            status = status
        else:
            status = status[1]
        dev_info_dict = {"name": device_data["mxlabel"], "code": device_data["code"],
                     "state": self.set_state(status), "local": self.db.get_local(
            self.model(device_type=self.db.device_type, iot_code=device_data["code"],
                       sroom_code="")),
                     "alarm_info": "", "mxdevicetype": device_data["mxdevicetype"], }
        # 获取告警数据
        for alert_dev_key, alert_info in self.db.get_alert_data().items():
            if re.search(device_data["code"].replace(".", "\."), alert_dev_key):
                dev_info_dict["alarm_info"] = alert_info
                break
        return dev_info_dict


class PowerDeviceListServer(PowerDeviceSelectServer):
    __db__ = PowerDeviceListDB

    def list(self, **kwargs):
        """

        @param kwargs:
        @return:
        """
        device_data_list = self.db.query_device()
        for device_data in device_data_list:
            status = GetStatusById(device_data["code"])
            if isinstance(status ,int):
                status = status
            else:
                status = status[1]
            device_data["state"] = self.set_state(status)
            if device_data.get("mxparent"):
                del device_data["mxparent"]
        return device_data_list


class PowerDeviceRetrieveServer(PowerDeviceSelectServer):
    __db__ = PowerDeviceRetrieveDB

    def list(self, **kwargs):
        """

        @param kwargs:
        @return:
        """
        device_data = self.db.select(**kwargs)
        device_type = device_data["mxdevicetype"].rsplit("\\", 1)[1]
        tmp = self.db.read_template()
        if not tmp.get(device_type):
            raise VerifyError(_("模板不存在"))
        device_type = tmp[device_type]["property"]
        device_data["code"] = kwargs["code"]
        # 获取 设备的基础信息
        device_info_dict = self.device_base_info(device_data)
        alarm_data = device_info_dict["alarm_data"] = []
        # 获取告警数据
        record_data = self.get_table_data(device_data["sub_monitor"], days=7, count=1)

        for device in device_type:
            record_dict = record_data[device["name"]]
            if not record_dict:
                continue
            alarm_data.append({"label": device["label"], "data": self.process_child(record_dict[0], device["child"])})
        return device_info_dict

    @staticmethod
    def process_child(record_dict: list, child):
        """
        设备的数据
        @param record_dict:
        @param child:
        @return:
        """
        res_list = []
        for child_dict in child:
            res_list.append(
                {"name": child_dict["mxlabel"], "value": record_dict[child_dict["code"]], "unit": child_dict["mxunit"]})
        return res_list
